package datatype;

import org.junit.Test;

import java.util.Iterator;

/**
 * @author DuJiabao
 * @create 2020-12-28 23:33
 */
public class LinkedListQueue<Item> implements Iterable<Item> {

    private int count = 0;
    private Node<Item> head;
    private Node<Item> tail;

    @Test
    public void test() {
        LinkedListQueue<Integer> linkedListQueue = new LinkedListQueue<Integer>();
        System.out.println(linkedListQueue.isEmpty());
        linkedListQueue.enqueue(100);
        linkedListQueue.enqueue(20);
        linkedListQueue.enqueue(130);
        System.out.println(linkedListQueue.isEmpty());
        System.out.println(linkedListQueue.size());
        linkedListQueue.forEach();
        System.out.println(linkedListQueue.dequeue());
        linkedListQueue.forEach();
        linkedListQueue.enqueue(200);
        linkedListQueue.forEach();
    }

    public void enqueue(Item item) {
        Node<Item> node = new Node<Item>(item, null);
        if (count == 0) {
            head = node;
        } else {
            tail.setNext(node);
        }
        tail = node;
        count++;
    }

    public Item dequeue() {
        if (count == 0) {
            return null;
        }
        Node<Item> node = head;
        head = head.getNext();
        count--;
        return node.getItem();
    }

    public boolean isEmpty() {
        return count == 0;
    }

    public int size() {
        return count;
    }

    @Override
    public Iterator<Item> iterator() {
        return new ListIterator();
    }

    private class ListIterator implements Iterator<Item> {
        private Node<Item> current = head;

        @Override
        public boolean hasNext() {
            return current != null;
        }

        @Override
        public Item next() {
            Item item = current.getItem();
            current = current.getNext();
            return item;
        }
    }

    public void forEach(){
        for(Node<Item> x = head;x != null;x=x.getNext()){
            System.out.println(x.getItem());
        }
    }
}
